/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JProcess.java
 *
 * Created on 2 Δεκ 2009, 1:22:42 πμ
 */
package com.panayotis.cafeports.gui.installer;

import com.panayotis.utilities.Closure;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JLabel;

/**
 *
 * @author teras
 */
public class JProcess extends javax.swing.JDialog {

    private StringBuffer err = new StringBuffer();
    private boolean exec_running = true;
    private boolean kill_request = false;
    private final Closure cancel;
    /* */
    private Timer totalT;
    private long last_total_time;
    private Timer stageT;
    private long last_stage_time;

    /** Creates new form JProcess */
    public JProcess(Closure cancel) {
        initComponents();
        LogB.setVisible(false);
        ScrollArea.setVisible(false);
        this.cancel = cancel;
        pack();
    }

    public void beginTimer() {
        last_total_time = System.currentTimeMillis();
        last_stage_time = last_total_time;
        totalT = new Timer();
        totalT.schedule(new TimerTask() {

            @Override
            public void run() {
                updateTimer(last_total_time, TotalTime);
            }
        }, 0, 1000);
        stageT = new Timer();
        stageT.schedule(new TimerTask() {

            @Override
            public void run() {
                updateTimer(last_stage_time, StageTime);
            }
        }, 0, 1000);
    }

    private void updateTimer(long last_time, JLabel TimeLabel) {
        long elapsed = Math.round((System.currentTimeMillis() - last_time) / 1000.0);
        TimeLabel.setText(elapsed + " secs");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        InfoP = new javax.swing.JPanel();
        InfoL = new javax.swing.JLabel();
        LowInfoP = new javax.swing.JPanel();
        TTimeL = new javax.swing.JLabel();
        TotalTime = new javax.swing.JLabel();
        STimeL = new javax.swing.JLabel();
        StageTime = new javax.swing.JLabel();
        LowerP = new javax.swing.JPanel();
        CloseB = new javax.swing.JButton();
        LogB = new javax.swing.JButton();
        ScrollArea = new javax.swing.JScrollPane();
        ErrorText = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("CaféPorts execute");
        setLocationByPlatform(true);
        setModal(true);
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(16, 16, 8, 16));
        jPanel1.setLayout(new java.awt.BorderLayout(0, 8));

        InfoP.setLayout(new java.awt.BorderLayout());

        InfoL.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/stages/default.png"))); // NOI18N
        InfoL.setText("Initializing ...");
        InfoL.setIconTextGap(16);
        InfoL.setMaximumSize(new java.awt.Dimension(480, 48));
        InfoL.setMinimumSize(new java.awt.Dimension(480, 48));
        InfoL.setPreferredSize(new java.awt.Dimension(480, 48));
        InfoP.add(InfoL, java.awt.BorderLayout.NORTH);

        LowInfoP.setBorder(javax.swing.BorderFactory.createEmptyBorder(8, 0, 0, 0));
        LowInfoP.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        TTimeL.setText("Total time");
        LowInfoP.add(TTimeL);
        LowInfoP.add(TotalTime);

        STimeL.setText("Stage time");
        STimeL.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 24, 0, 0));
        LowInfoP.add(STimeL);
        LowInfoP.add(StageTime);

        InfoP.add(LowInfoP, java.awt.BorderLayout.PAGE_END);

        jPanel1.add(InfoP, java.awt.BorderLayout.NORTH);

        LowerP.setLayout(new java.awt.BorderLayout());

        CloseB.setText("Cancel");
        CloseB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CloseBActionPerformed(evt);
            }
        });
        LowerP.add(CloseB, java.awt.BorderLayout.EAST);

        LogB.setForeground(new java.awt.Color(204, 51, 0));
        LogB.setText("Show Error log");
        LogB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LogBActionPerformed(evt);
            }
        });
        LowerP.add(LogB, java.awt.BorderLayout.WEST);

        jPanel1.add(LowerP, java.awt.BorderLayout.SOUTH);

        ScrollArea.setPreferredSize(new java.awt.Dimension(244, 240));

        ErrorText.setColumns(20);
        ErrorText.setRows(5);
        ScrollArea.setViewportView(ErrorText);

        jPanel1.add(ScrollArea, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CloseBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseBActionPerformed
        if (exec_running) {
            cancel.exec(null);
            CloseB.setEnabled(false);
            kill_request = true;
        } else
            setVisible(false);
    }//GEN-LAST:event_CloseBActionPerformed

    private void LogBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogBActionPerformed
        ScrollArea.setVisible(true);
        LogB.setVisible(false);
        setResizable(true);
        pack();
    }//GEN-LAST:event_LogBActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CloseB;
    private javax.swing.JTextArea ErrorText;
    private javax.swing.JLabel InfoL;
    private javax.swing.JPanel InfoP;
    private javax.swing.JButton LogB;
    private javax.swing.JPanel LowInfoP;
    private javax.swing.JPanel LowerP;
    private javax.swing.JLabel STimeL;
    private javax.swing.JScrollPane ScrollArea;
    private javax.swing.JLabel StageTime;
    private javax.swing.JLabel TTimeL;
    private javax.swing.JLabel TotalTime;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

    public void updateStatus(String line) {
        if (IconFactory.shoudUpdateDisplay(line)) {
            InfoL.setIcon(IconFactory.getIconByLine(line));
            InfoL.setText(IconFactory.getIconText(line));
            last_stage_time = System.currentTimeMillis();
        }
    }

    void updateError(String line) {
        LogB.setVisible(true);
        err.append(line).append('\n');
        ErrorText.setText(err.toString());
    }

    void finishExec() {
        exec_running = false;
        totalT.cancel();
        stageT.cancel();
        STimeL.setVisible(false);
        StageTime.setVisible(false);

        if (kill_request)
            setVisible(false);
        else {
            if (err.length() > 0) {
                InfoL.setIcon(IconFactory.getIconByName(IconFactory.ERROR_ICON));
                InfoL.setText("Error while performing action.");
            } else {
                InfoL.setIcon(IconFactory.getIconByName(IconFactory.OK_ICON));
                InfoL.setText("Action finished with no errors.");
            }
            CloseB.setText("Close");
        }
    }
}
